//
//  JDDetailVC.swift
//  LeGou
//
//  Created by 刘亿前 on 2022/9/20.
//

import UIKit

class PddDetailVC: ZMViewController {
    
    //MARK:--------------------UI控件--------------------
    @IBOutlet weak var navView: NavigationBarView!
    
    // 服务商提示
    @IBOutlet weak var vipContent: UIView!
    @IBOutlet weak var vipTip: UILabel!
    
    @IBOutlet weak var banner: SDCycleScrollView!

    @IBOutlet weak var bottomContent: UIView!
    
    @IBOutlet weak var scrollView: ScrollBgView!
    
    let goodsList = HomeListVC()
    
    @IBOutlet weak var someItemView: UIView!
    
    @IBOutlet weak var goodsContentH: NSLayoutConstraint!
    
    // 原价
    @IBOutlet weak var subPrice: UILabel!
    // 价格
    @IBOutlet weak var price: UILabel!
    // 销量
    @IBOutlet weak var saleCount: UILabel!
    // 名称
    @IBOutlet weak var name: UILabel!
    // 反多少
    @IBOutlet weak var couponPrice: UILabel!
    
    // 优惠券容器视图
    @IBOutlet weak var couponContentView: UIView!
    // 优惠券金额
    @IBOutlet weak var couponMoney: UILabel!
    // 优惠券名称
    @IBOutlet weak var couponName: UILabel!
    // 优惠券日期
    @IBOutlet weak var couponDate: UILabel!
    
    @IBOutlet weak var detailContent: TBDetailView!
    // 猜你喜欢父容器
    @IBOutlet weak var gussYLikeContent: UIView!
    @IBOutlet weak var likeList: UICollectionView!
    @IBOutlet weak var likeHeight: NSLayoutConstraint!
    
    // 首页
    @IBOutlet weak var homeView: UIStackView!
    // 收藏
    @IBOutlet weak var collectView: UIStackView!
    @IBOutlet weak var collectImg: UIImageView!
    // 分享赚
    @IBOutlet weak var shareBtn: UIButton!
    // 自购省
    @IBOutlet weak var buyBtn: UIButton!
    
    lazy var shareView: DetailShareView = {
        let v = DetailShareView()
        view.addSubview(v)
        v.snp.makeConstraints { make in
            make.bottom.equalTo(bottomContent.snp.top).offset(-5)
            make.centerX.equalToSuperview()
        }
        return v
    }()
    
    var goodsSign = ""
    var catId = 0
    var page = 1
    let pageSize = 10
    var detailInfo = PDDModel()
    var likeArr = [PDDModel]()
//    var userCommission = 0.01
//    var userShareCommission = 0.01

    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        setCollection()
        requestDetail()
        requestLike()
        bindAction()
    }
    
    func setUI() {
        title = ""
        hbd_barHidden = true
        buyBtn.titleLabel?.numberOfLines = 0
        buyBtn.titleLabel?.textAlignment = .center
        shareBtn.titleLabel?.numberOfLines = 0
        shareBtn.titleLabel?.textAlignment = .center
        collectView.isHidden = true
        couponContentView.isHidden = true
        gussYLikeContent.isHidden = true
        navView.contentView.backgroundColor = .clear
        navView.backgroundColor = .clear
        navView.autoBack = true
        navView.backButton.setImage(UIImage.init(named: "detail_back"), for: .normal)
        navView.backButton.backgroundColor = UIColor.zm.RGBA(r: 0, g: 0, b: 0, a: 0.55)
        navView.backButton.snp.updateConstraints { make in
            make.width.height.equalTo(36)
        }
        navView.backButton.layer.cornerRadius = 18
        addRefresh(scrollView: scrollView, addHead: false) { [unowned self] refresh in
            self.page += 1
            self.requestLike()
        }
        scrollView.mj_footer?.isHidden = true
        if AppHelper.appVerify() {
            vipContent.isHidden = true
        }
    }
    
    func setCollection() {
        let layout = HomeHotFlowLayout()
        layout.minimumLineSpacing = 7
        layout.minimumInteritemSpacing = 7
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsets(top: 16, left: 12, bottom: 18, right: 12)
        layout.delegate = self
        likeList.delegate = self
        likeList.dataSource = self
        likeList.setCollectionViewLayout(layout, animated: true)
        likeList.register(UINib(nibName: "HomeGoodsCell", bundle: nil), forCellWithReuseIdentifier: "HomeGoodsCell")
    }
    
    func setData() {
        banner.pageDotColor = "#999999".zm.hex()
        banner.currentPageDotColor = Style.mainColor
        banner.bannerImageViewContentMode = .scaleAspectFill
        banner.autoScroll = false
        banner.imageURLStringsGroup = detailInfo.goodsGalleryUrls
        
        
        price.attributedText = "¥".zm.attributedStr(attrs: [.font : Style.FONT_Open_Sans_SemiBold(14)])
            .zm.append(str: detailInfo.currentPrice.zm.toString(keep: 2), attri: ["f" : Style.FONT_Open_Sans_SemiBold(22)])
        subPrice.zm.setStrikethroughTitle(title: "¥\(detailInfo.oldPrice.zm.toString(keep: 2))")
        name.text = detailInfo.goodsName
        saleCount.text = "销量：" + detailInfo.salesTip
        couponPrice.text = detailInfo.refundMoney(detailInfo.userShareCommission) + "元"
        
        if detailInfo.hasCoupon {
            couponContentView.isHidden = false
            couponMoney.text = detailInfo.couponPrice.zm.toString(keep: 2)
            couponDate.text = "\(detailInfo.couponStartTime)".zm.stampToString(formate: "YYYY.MM.dd") + "-" + "\(detailInfo.couponEndTime)".zm.stampToString(formate: "YYYY.MM.dd")
        }
        detailContent.loadImages(dataSorce: detailInfo.goodsGalleryUrls)
        if let user = ZMAppShareData.share.userInfo.value, user.serviceProviderLevel > 0 {
            vipTip.text = "服务商\(MineService.shared.LevelStr(level: user.serviceProviderLevel)), 可赚到共富收益月入10万+"
        } else {
            vipTip.text = "升级VIP，可赚到共富收益月入10万+"
        }
        if detailInfo.userShareCommission > 0 {
            self.shareView.title.text = "分享给好友购买赚\((detailInfo.refundMoney(detailInfo.userShareCommission).zm.hk_toDouble() * 10.0).zm.toString(keep: 2))额度"
            self.shareBtn.setTitle("分享赚¥\(detailInfo.refundMoney(detailInfo.userShareCommission))", for: .normal)
        } else {
            self.shareBtn.setTitle("分享赚", for: .normal)
        }
        let userCommission = detailInfo.refundMoney(detailInfo.userCommission).zm.hk_toDouble() + detailInfo.couponPrice
        if userCommission > 0 {
            self.buyBtn.setTitle("自购省¥\(userCommission.zm.toString(keep: 2))", for: .normal)
        } else {
            self.buyBtn.setTitle("自购省", for: .normal)
        }
    }
    
    func giveSize(titleStr : String) -> CGSize {
        let imageStr = getAtrStr(titleStr: titleStr)
        let width = (SCREEN_W - 24 - 7 ) / 2 - 24
        imageStr.addAttributes([.font : UIFont.systemFont(ofSize: 14, weight: .medium)], range: NSRange(location: 0, length: imageStr.length))
        var size = imageStr.boundingRect(with: CGSize(width: width, height: 45), options: .usesLineFragmentOrigin, context: nil).size
        if size.height > 45 {
            size.height = 45
        }
        return size
    }
    
    func getAtrStr(titleStr : String) -> NSMutableAttributedString {
        let att = NSTextAttachment.init(data: nil, ofType: nil)
        att.image = UIImage.init(named: "home_jd")
        att.bounds = CGRect(x: 0, y: -4, width: 20, height: 20)
        let imageStr = NSMutableAttributedString(attachment: att)
        imageStr.append(NSMutableAttributedString.init(string: titleStr))
        return imageStr
    }
    
    // MARK: - bindAction
    func bindAction() {
        likeList.rx.observeWeakly(CGSize.self, "contentSize").subscribe(onNext: { [unowned self] (change) in
            self.likeHeight.constant = change!.height
        }).disposed(by: disposeBag)
        
        // 首页
        let homeTap = UITapGestureRecognizer()
        homeView.addGestureRecognizer(homeTap)
        homeTap.rx.event.subscribe(onNext: { [unowned self] recognizer in
            CATransaction.setCompletionBlock {
                guard let tab = UIApplication.shared.keyWindow?.rootViewController as? UITabBarController else {return}
                tab.selectedIndex = 0
            }
            CATransaction.begin()
            navigationController?.popToRootViewController(animated: true)
            CATransaction.commit()
        }).disposed(by: disposeBag)
        
        buyBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            self.requestLink(type: "2")
        }).disposed(by: disposeBag)
        
        let couponContentViewTap = UITapGestureRecognizer()
        couponContentView.addGestureRecognizer(couponContentViewTap)
        couponContentViewTap.rx.event.subscribe(onNext: { [unowned self] recognizer in
            self.requestLink()
        }).disposed(by: disposeBag)
        
        shareBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            self.requestLink(share: true)
        }).disposed(by: disposeBag)
    }
    
    @IBAction func onLevelUp(_ sender: UIButton) {
        tabBarController?.selectedIndex = 1
        self.navigationController?.popToRootViewController(animated: true)
//        router.push("xm://main/Mine/user_level")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        likeList.reloadData()
    }
}

extension PddDetailVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, HomeHotFlowLayoutDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return likeArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width : CGFloat = (SCREEN_W - 24 - 7) / 2
        let d = likeArr[indexPath.row]
        let size = giveSize(titleStr: d.goodsName)
        return CGSize(width: width, height: width + 15 + size.height + HomeGoodsCell.bootomH)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeGoodsCell", for: indexPath) as! HomeGoodsCell
        cell.pddUI(likeArr[indexPath.row])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vc = PddDetailVC()
        if likeArr[indexPath.row].catIds.count > 0 {
            vc.catId = likeArr[indexPath.row].catIds[0]
        }
        vc.goodsSign = likeArr[indexPath.row].goodsSign
        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - Request Action
extension PddDetailVC {
    func requestDetail() {
        ZMToast.showActivity()
        PddAPI.pdd_detail(["goodsSign":goodsSign]).rxRequest(type: PDDModel.self).subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
//            self.userCommission = resp.userCommission
//            self.userShareCommission = resp.userShareCommission
            self.detailInfo = resp
            self.setData()
        }).disposed(by: disposeBag)
    }
    
    func requestLike() {
        let pa = ["page":page, "limit":pageSize,"goodsSign":goodsSign,"catId":catId] as [String : Any]
        ZMUtil.listRequest(type: PDDModel.self, api: PddAPI.pdd_detail_like(pa)) { resp in
            if resp.code == .success {
                if let data = resp.data {
                    self.gussYLikeContent.isHidden = false
                    self.likeArr.append(contentsOf: data)
                    self.likeList.reloadData()
                    self.scrollView.mj_footer?.endRefreshing()
                    if data.count < self.pageSize {
                        self.scrollView.mj_footer?.isHidden = true
                    } else {
                        self.scrollView.mj_footer?.isHidden = false
                    }
                } else {
                    self.scrollView.mj_footer?.isHidden = true
                }
            }
        }
        
//        let pa = ["page":page, "limit":pageSize,"goodsSign":goodsSign,"catId":catId] as [String : Any]
//        PddAPI.pdd_detail_like(pa).rxRequestNullAble(type: PDDListModel.self).subscribe(onNext:{ [unowned self] resp in
//            if let data = resp, data.searchGoodsList.count > 0 {
//                if self.page == 1 {
//                    self.likeArr.removeAll()
//                }
//                self.likeArr.append(contentsOf: data.searchGoodsList)
//                if data.searchGoodsList.count < pageSize {
//                    self.scrollView.mj_footer?.endRefreshingWithNoMoreData()
//                } else {
//                    self.scrollView.mj_footer?.endRefreshing()
//                }
//                if let header = self.scrollView.mj_header,header.isRefreshing {
//                    header.endRefreshing()
//                }
//                self.likeList.reloadData()
//            }
//        }).disposed(by: disposeBag)
    }

    func requestLink(type: String = "2", share: Bool = false) {
        if LoginService.shared.checkLogin() == false {return}
        ZMToast.showActivity()
        let pa = ["goodsId":goodsSign,"promtionType":type] as [String : Any]
        PddAPI.pdd_link(pa).rxRequestNullAble(type: PDDLinkModel.self).subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            if let data = resp {
//                if data.bind == false {
//                    PDDAuthTip.show {
//                        if let url = URL(string: data.shortUrl) {
//                            if #available(iOS 10, *) {
//                                UIApplication.shared.open(url)
//                            } else {
//                                UIApplication.shared.openURL(url)
//                            }
//                        } else {
//                            ZMToast.showToast(title: "转链失败")
//                        }
//                    }
//                    return
//                }
                if share {
                    let v = ZMUtil.loadNibViewFullScreen(nibName: TBSharePOPView.self)
                    v.pddGoodsInfo.accept(self.detailInfo)
                    v.linkInfo.accept(TBLinkInfo(shortUrl: data.shortUrl))
                    self.view.addSubview(v)
                } else {
                    if let url = URL(string: data.shortUrl) {
                        if #available(iOS 10, *) {
                            UIApplication.shared.open(url)
                        } else {
                            UIApplication.shared.openURL(url)
                        }
                    } else {
                        ZMToast.showToast(title: "没有商品链接")
                    }
                }
            } else {
                ZMToast.showToast(title: "转链失败")
            }
        }).disposed(by: disposeBag)
    }
}
